//
//  EquipModelVC.m
//  运营管理系统
//
//  Created by 杨毅 on 17/1/11.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "EquipModelVC.h"

@interface EquipModelVC ()
{
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
    NSMutableArray *_dataSource;
    UIButton *_starTimeTF;
    UIButton *_stopTimeTF;
    NSInteger tag;
    NSDictionary *_paramet;
    NSInteger userID;
    NSInteger pageNum;
    NSInteger searchStata;//0没点击搜索 1点击了搜索
}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation EquipModelVC
- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _paramet = @{@"type":@8,@"userId":[NSString stringWithFormat:@"%ld",userID],@"pageNum":@0};
    [self load];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    userID = dele.userId;

    _dataSource = [[NSMutableArray alloc]init];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = UIColorFromRGB(0xe6e6e6);
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];
    UIView *heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 70)];
    heardView.backgroundColor = [UIColor whiteColor];
    UILabel *timeLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 7, 25, 21)];
    timeLab.text = @"📅";
    timeLab.font = [UIFont systemFontOfSize:15.0];
    timeLab.textColor = UIColorFromRGB(0x4d4d4d);
    [heardView addSubview:timeLab];
    
    _starTimeTF = [UIButton buttonWithType:UIButtonTypeSystem];
    _starTimeTF.frame = CGRectMake(40, 5, (kSCREEN_WIDTH-98)/2, 25);
    [_starTimeTF setTitle:@"选择开始时间" forState:UIControlStateNormal];
    [_starTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
    _starTimeTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _starTimeTF.titleLabel.font = [UIFont systemFontOfSize:15.0];
    _starTimeTF.layer.cornerRadius = 5;
    //btn标题对齐方式
    _starTimeTF.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_starTimeTF addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    _starTimeTF.tag = 1001;
    [heardView addSubview:_starTimeTF];
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_starTimeTF.frame), CGRectGetMinY(_starTimeTF.frame), 8, 21)];
    line.text = @"-";
    line.textColor = UIColorFromRGB(0xb6b6b6);
    [heardView addSubview:line];
    
    
    _stopTimeTF = [UIButton buttonWithType:UIButtonTypeSystem];
    _stopTimeTF.frame = CGRectMake(CGRectGetMaxX(line.frame), 5, (kSCREEN_WIDTH-98)/2, 25);
    [_stopTimeTF setTitle:@"选择结束时间" forState:UIControlStateNormal];
    [_stopTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
    _stopTimeTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _stopTimeTF.titleLabel.font = [UIFont systemFontOfSize:15.0];
    _stopTimeTF.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _stopTimeTF.layer.cornerRadius = 5;
    [_stopTimeTF addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
    _stopTimeTF.tag = 1002;
    [heardView addSubview:_stopTimeTF];
    UIButton *SearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    SearchBtn.frame = CGRectMake(CGRectGetMaxX(_stopTimeTF.frame)+10, 5, 25, 25);
    [SearchBtn setImage:[[UIImage imageNamed:@"seach_icon_b"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [SearchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [heardView addSubview:SearchBtn];
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 39, kSCREEN_WIDTH, 1)];
    line1.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [heardView addSubview:line1];
    UILabel *CompanyT = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, kSCREEN_WIDTH-185, 21)];
    CompanyT.text = @"设备型号";
    CompanyT.textColor = UIColorFromRGB(0x0093d5);
    [heardView addSubview:CompanyT];
    UILabel *GzNumb = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(CompanyT.frame), 45, 80, 21)];
    GzNumb.text = @"故障数";
    GzNumb.textColor = UIColorFromRGB(0x0093d5);
    GzNumb.textAlignment = NSTextAlignmentCenter;
    [heardView addSubview:GzNumb];
    UILabel *proportion = [[UILabel alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-90, 45, 80, 21)];
    proportion.text = @"比例(%)";
    proportion.textColor = UIColorFromRGB(0x0093d5);
    proportion.textAlignment = NSTextAlignmentCenter;
    [heardView addSubview:proportion];
    _tableView.tableHeaderView = heardView;
    
    [self.view addSubview:_tableView];
    searchStata = 1;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSource removeAllObjects];
        searchStata = 0;
        pageNum = 0;
        _paramet = @{@"type":@8,@"userId":[NSString stringWithFormat:@"%ld",userID],@"pageNum":[NSString stringWithFormat:@"%ld",pageNum]};
        [_starTimeTF setTitle:@"选择开始时间" forState:UIControlStateNormal];
        [_starTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
        [_stopTimeTF setTitle:@"选择结束时间" forState:UIControlStateNormal];
        [_stopTimeTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
        
        [self load];
    }];
    
    
    
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        pageNum = pageNum + 1;
        if (searchStata == 1) {
            _paramet = @{@"type":@8,@"userId":[NSString stringWithFormat:@"%ld",userID],@"pageNum":[NSString stringWithFormat:@"%ld",pageNum]};
        }else{
            _paramet = @{@"type":@8,@"userId":[NSString stringWithFormat:@"%ld",userID],@"startTime":_starTimeTF.titleLabel.text,@"endTime":_stopTimeTF.titleLabel.text,@"pageNum":[NSString stringWithFormat:@"%ld",pageNum]};
        }
        
        [self load];
    }];


}
/**
 *  停止刷新
 */
-(void)endRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)load{
    if (searchStata == 1) {
        if (![_starTimeTF.titleLabel.text isEqualToString:@"选择开始时间"] || ![_stopTimeTF.titleLabel.text isEqualToString:@"选择结束时间"]) {
            searchStata = 0;
        }else{
            searchStata = 1;
        }
    }else{
        if (![_starTimeTF.titleLabel.text isEqualToString:@"选择开始时间"] || ![_stopTimeTF.titleLabel.text isEqualToString:@"选择结束时间"]) {
            searchStata = 1;
        }else{
            searchStata = 0;
        }
    }

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_GZcount parameters:_paramet progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYEquipDataModel *dataModel = [[YYEquipDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYEquipListModel *model in dataModel.modelList) {
            [_dataSource addObject:model];
        }
        /*NSArray *Pson = dic[@"data"][@"Pson"];
         
         NSArray *colorArr = @[@"ff9429",
         @"e94f25",
         @"00b0ec",
         @"006db8",
         @"fdd100"];
         for (NSInteger i = 0; i < Pson.count; ++i) {
         
         
         PsonModel *model = [[PsonModel alloc]init];
         model.percent = [Pson[i][@"percent"]floatValue];
         model.pson = Pson[i][@"pson"];
         model.value = [Pson[i][@"value"]integerValue];
         [_dataSource addObject:model];
         
         NSDictionary *dic1 = @{@"number":[NSString stringWithFormat:@"%.f%c",[Pson[i][@"percent"]floatValue]*100,'%'],@"color":colorArr[i%5],@"name":Pson[i][@"pson"]};
         
         
         
         [_value addObject:dic1];
         
         }*/
        
        //[self initScorll];
        if (_dataSource.count == 0) {
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110) title:@"不好...暂时没有数据,点击刷新返回原始数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self endRefresh];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 110, kSCREEN_WIDTH, kSCREEN_HEIGHT-110)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}
- (void)NothingRefresh:(UIButton *)sender{
    
    [_nothing removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
- (void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self.tableView.mj_header beginRefreshing];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return _dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 44.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //GZcountPsonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    
    EquipModelCell *cell = [[EquipModelCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    cell.backgroundColor = UIColorFromRGB(0xf0f0f0);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YYEquipListModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}
- (void)chooseTime:(UIButton *)sender{
    
    tag = sender.tag;
    
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    
    calendarController.delegate = self;
    NSArray *arr = [sender.titleLabel.text componentsSeparatedByString:@"-"];
    
    if (arr.count > 1) {
        [calendarController setYear:arr[0] month:arr[1] day:arr[2]];
    }
    
    [self presentViewController:calendarController animated:YES completion:nil];
    
}
-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    
    if (tag == 1001) {
        
        if (day.length == 1 && month.length != 1) {
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-0%@", year, month,day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length != 1){
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-%@", year, month, day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length ==1 ){
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-0%@", year, month, day] forState:UIControlStateNormal];
        } else{
            
            [_starTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-%@", year, month, day] forState:UIControlStateNormal];
        }
        [_starTimeTF setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        
    }else{
        
        if (day.length == 1 && month.length != 1) {
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-0%@", year, month,day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length != 1){
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-%@", year, month, day] forState:UIControlStateNormal];
        }else if (month.length == 1 && day.length ==1 ){
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-0%@-0%@", year, month, day] forState:UIControlStateNormal];
        } else{
            
            [_stopTimeTF setTitle:[NSString stringWithFormat:@"%@-%@-%@", year, month, day] forState:UIControlStateNormal];
        }
        [_stopTimeTF setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    }
    
    
}

- (void)searchClick{
    if ([_starTimeTF.titleLabel.text isEqualToString:@"选择开始时间"] || [_stopTimeTF.titleLabel.text isEqualToString:@"选择结束时间"]) {
        [self showAlert:@"温馨提示" message:@"请完善搜索条件" actionWithTitle:@"确定"];
    }else{
        [_dataSource removeAllObjects];
        _paramet = @{@"type":@8,@"userId":[NSString stringWithFormat:@"%ld",userID],@"startTime":_starTimeTF.titleLabel.text,@"endTime":_stopTimeTF.titleLabel.text,@"pageNum":@0};
        [self load];
    }
    
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
